package com.shigu.user.service;

import com.opentae.data.mall.beans.MallToken;
import com.opentae.data.mall.examples.MallTokenExample;
import com.opentae.data.mall.interfaces.MallTokenMapper;
import com.shigu.exceptions.WapException;
import com.shigu.user.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 郭尔
 * @description 用户token相关服务
 * @date 2019/2/18 10:14
 */

@Service
public class MallTokenService {
    @Autowired
    MallTokenMapper mallTokenMapper;

    /**
     * @description 根据token查询用户id
     * @author 郭尔
     * @date 2019/2/18 12:16
     */
    @Cacheable(value = "mall_token", key = "#token")
    public Long selUserIdByToken(String token) {
        return mallTokenMapper.selUserIdByToken(token);
    }

    /**
     * @description 根据用户id 获取token
     * @author 郭尔
     * @date 2019/2/18 13:13
     */
    public synchronized String userIdToToken(Long userId) {
        MallTokenExample example = new MallTokenExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<MallToken> userTokens = mallTokenMapper.selectByExample(example);
        //token表为空
        if (userTokens.size() == 0) {
            String uuid = UUIDUtils.getUUID();
            MallToken mallToken = new MallToken();
            mallToken.setUserId(userId);
            mallToken.setToken(uuid);
            mallToken.setTokenDate(new Date());
            try {
                mallTokenMapper.insertSelective(mallToken);
            } catch (Exception e) {
                uuid = UUIDUtils.getUUID();
                mallToken.setUserId(userId);
                mallToken.setToken(uuid);
                mallToken.setTokenDate(new Date());
                mallTokenMapper.insertSelective(mallToken);
            }
            return uuid;
        }
        return userTokens.get(0).getToken();
    }


}
